﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using ERPWinFormWork.Test.Test.Dtos;
using ERPWinFormWork.Test.Test.Dtos.Write;
using ERPWinFormWork.Test.TestCode;

namespace ERPWinFormWork.Test
{
    public partial class AddTesting_Items : Form
    {
        private ApiClient _apiClient;
        private Action _onSuccessCallback; // 添加成功后的回调函数

        public AddTesting_Items(Action onSuccessCallback = null)
        {
            _onSuccessCallback = onSuccessCallback;
            InitializeComponent();

            // 初始化 API 客户端
            _apiClient = new ApiClient(TestAPI.TestApiBaseUrl);

            // 绑定按钮事件
            this.btnAddTest.Click += btnAddTest_Click;

            // 加载下拉框数据
            LoadDetectionTypeData();
            LoadTestingToolsData();
        }

        /// <summary>
        /// 加载检测类型下拉框数据
        /// </summary>
        private async Task LoadDetectionTypeData()
        {
            try
            {
                var response = await _apiClient.GetAsync<TestApiResult<List<Detection_TypeDtos>>>(
                    endpoint: "api/Read/GetDetection_Type");

                if (response != null && response.code == 200)
                {
                    cbodetection_TypeId.Items.Clear();
                    cbodetection_TypeId.DisplayMember = "detectionType_Name";
                    cbodetection_TypeId.ValueMember = "id";
                    cbodetection_TypeId.DataSource = response.data;
                    cbodetection_TypeId.SelectedItem = null;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载检测类型数据失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 加载检测工具下拉框数据
        /// </summary>
        private async Task LoadTestingToolsData()
        {
            try
            {
                var response = await _apiClient.GetAsync<TestApiResult<List<Testing_ToolsDtos>>>(
                    endpoint: "api/Read/GetTesting_Tools");

                if (response != null && response.code == 200)
                {
                    cbotesting_ToolsId.Items.Clear();
                    cbotesting_ToolsId.DisplayMember = "tools_Name";
                    cbotesting_ToolsId.ValueMember = "id";
                    cbotesting_ToolsId.DataSource = response.data;
                    cbotesting_ToolsId.SelectedItem = null;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载检测工具数据失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 验证表单数据
        /// </summary>
        /// <returns>验证是否通过</returns>
        private bool ValidateForm()
        {
            // 验证检测项目名称
            if (string.IsNullOrWhiteSpace(textitems_Name.Text?.Trim()))
            {
                MessageBox.Show("请输入检测项目名称", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                textitems_Name.Focus();
                return false;
            }

            // 验证检测类型
            if (cbodetection_TypeId.SelectedValue == null)
            {
                MessageBox.Show("请选择检测类型", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                cbodetection_TypeId.Focus();
                return false;
            }

            // 验证检测工具
            if (cbotesting_ToolsId.SelectedValue == null)
            {
                MessageBox.Show("请选择检测工具", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                cbotesting_ToolsId.Focus();
                return false;
            }

            return true;
        }

        /// <summary>
        /// 提交按钮点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void btnAddTest_Click(object sender, EventArgs e)
        {
            // 验证表单
            if (!ValidateForm())
            {
                return;
            }

            // 构建请求数据
            var requestData = new CreateTesting_ItemsDtos
            {
                items_Name = textitems_Name.Text?.Trim(),
                detection_TypeId = (int)cbodetection_TypeId.SelectedValue,
                testing_ToolsId = (int)cbotesting_ToolsId.SelectedValue
            };

            // 调用API创建检测项
            var response = await _apiClient.PostAsync<object, TestApiResult<string>>("api/Write/CreateTesting_Items", requestData
            );

            if (response != null && response.code == 200)
            {
                MessageBox.Show("检测项添加成功", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);

                // 调用回调函数刷新父窗体数据
                _onSuccessCallback?.Invoke();

                // 关闭当前窗体
                this.Close();
            }
            else
            {
                MessageBox.Show($"添加失败：{response?.msg ?? "接口调用失败"}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }
}
